local socket = require "socket"

local udp = socket.udp()
udp:settimeout(0)
udp:setsockname('*', 12345)

local world = {}
local data, msg_or_ip, port_or_nil
local id, cmd, parms
local running = true

print "Beginning server loop."
while (running) do
  data, msg_or_ip, port_or_nil = udp:receivefrom()
  if (data) then
    local id, cmd, params = data:match("^(%i*) (%S*) (.*)")
    print(id, cmd, parms)
    --id, cmd, parms = data:match("^(%I*) (%S*) (.*)")
    if (cmd == "createplayer") then
      local posx, posy, velx, vely = params:match("(%i*) (%i*) (%f*) (%f*)")
      posx, posy = tonumber(posx), tonumber(posy)
      --local id = world[id] or {posx=0, posy=0}
      world[id] = {posx=posx, posy=posy}
      for k, v in pairs(world) do
        udp:sendto(string.format("%i %s %i %i %f %f", id, 'createplayer', posx, posy, velx, vely), msg_or_ip,  port_or_nil)
      end
    elseif (cmd == "update") then
      print("farts")
      local posx, posy, velx, vely = params:match("(%i*) (%i*) (%f*) (%f*)")
      posx, posy = tonumber(posx), tonumber(posy)
      --local id = world[id] or {posx=0, posy=0}
      world[id] = {posx=id.posx, posy=id.posy}
      for k, v in pairs(world) do
        udp:sendto(string.format("%i %s %i %i %f %f", k, 'update', v.posx, v.posy, v.velx, v.vely), msg_or_ip,  port_or_nil)
      end
    else
      --print("unrecognised command:", cmd)
    end
        --[[entity, cmd, parms = data:match("^(%S*) (%S*) (.*)")
        if cmd == 'move' then
            local x, y = parms:match("^(%-?[%d.e]*) (%-?[%d.e]*)$")
            assert(x and y)
            x, y = tonumber(x), tonumber(y)
            local ent = world[entity] or {x=0, y=0}
            world[entity] = {x=ent.x+x, y=ent.y+y}
        elseif cmd == 'at' then
            local x, y = parms:match("^(%-?[%d.e]*) (%-?[%d.e]*)$")
            assert(x and y)
            x, y = tonumber(x), tonumber(y)
            world[entity] = {x=x, y=y}
        elseif cmd == 'update' then
            for k, v in pairs(world) do
              udp:sendto(string.format("%s %s %d %d", k, 'at', v.x, v.y), msg_or_ip,  port_or_nil)
            end
        elseif cmd == 'quit' then
          running = false;
        elseif cmd == 'createplayer' then
          CreatePlayer()
        else
            print("unrecognised command:", cmd)
        end]] -- USELESS CRAP
  elseif (msg_or_ip ~= 'timeout') then
      error("Unknown network error: "..tostring(msg))
  end 
  socket.sleep(0.01)
end

function NewID()
  local newid = table.getn(world)
  if (table.getn(world) ~= nil) then
    newid = table.getn(world) + 1
  end
  world[newid] = nil
  return newid
end

print "Thank you."